# File lib/scape.rb, line 6 def initialize(patches) @patches = patches precompute_indices end
# File lib/scape.rb, line 11 def do_time_step @patches.each do |row| row.each do |patch| # Update patches patch.do_time_step # Repopulate depleted patch resources replenish_resources(patch) end end end
# File lib/scape.rb, line 68 def height @patches.empty? ? 0 : @patches.max_by { |x| x.size }.size end
Locates neighbours in a square pattern within the specified radius Specifying a radius of -1 returns all the patches in the scape
# File lib/scape.rb, line 50 def neighbours(patch, radius) if radius == -1 @flat_patches = patches.flatten if @flat_patches.nil? # Lazy evaluation return @flat_patches end x, y = @indices[patch] x0 = [x - radius, 0].max x1 = x + radius + 1 # Ruby arrays don't wrap around from the end y0 = [y - radius, 0].max y1 = y + radius + 1 @patches.slice(x0, x1).map { |row| row.slice(y0, y1) }.flatten end
# File lib/scape.rb, line 72 def precompute_indices @indices = {} @patches.each_with_index do |row, x| row.each_with_index do |patch, y| @indices[patch] = [x, y] if patch end end end
# File lib/scape.rb, line 24 def replenish_resources(patch) patch.resources.each do |resource| if resource.depleted? && resource.repopulation_chance > 0 # For each surrounding patch there is a certain chance the patch will be replenished neighbours(patch, 1).each do |neighbour| if neighbour.viable?(resource.name) && chance(resource.repopulation_chance) resource.repopulate break end end end end end
Calculates the total amount
# File lib/scape.rb, line 82 def resource_consumption counts = {} @patches.each do |col| col.each do |patch| patch.resources.each do |resource| counts[resource.name] = counts.fetch(resource.name, 0) + resource.energy_harvested end end end counts end
# File lib/scape.rb, line 38 def to_s out_string = "" @patches.each_with_index do |col, x| col.each_with_index do |patch, y| out_string << "(#{x}, #{y}): #{patch}\n" end end out_string end
# File lib/scape.rb, line 64 def width @patches.size end